<template>
  <view>
    <u--form class="form" labelPosition="left" :model="formData" :rules="rules" ref="form" labelWidth="80">
      <u-form-item label="昵称" prop="nickname" borderBottom>
        <u--input v-model="formData.nickname" border="none" clearable placeholder="请输入昵称"></u--input>
      </u-form-item>
      <u-form-item label="用户名" prop="username" borderBottom>
        <u--input v-model="formData.username" border="none" clearable placeholder="请输入用户名"></u--input>
      </u-form-item>
      <u-form-item label="密码" prop="password" borderBottom>
        <u--input type="password" v-model="formData.password" border="none" clearable placeholder="请输入密码"></u--input>
      </u-form-item>
      <u-form-item label="确认密码" prop="confirmPwd" borderBottom>
        <u--input type="password" v-model="formData.confirmPwd" border="none" clearable placeholder="请输入确认密码"></u--input>
      </u-form-item>
    </u--form>
    <u-button text="注册" @click="submit" />
  </view>
</template>

<script>
  export default {
    data() {
      return {
        formData: {
          username: '',
          password: '',
          confirmPwd: '',
          nickname: ''
        },
        rules: {
          nickname: {
            type: 'string',
            required: true,
            message: '请输入昵称',
            trigger: ['blur', 'change']
          },
          'username': {
            type: 'string',
            required: true,
            message: '请输入用户名',
            trigger: ['blur', 'change']
          },
          'password': [
            {
              type: 'string',
              required: true,
              message: '请输入密码',
              trigger: ['blur', 'change']
            },
            {
              min: 6,
              message: '密码最小长度为6个字符',
            }
          ],
          'confirmPwd': [
            {
              type: 'string',
              required: true,
              message: '请输入确认密码',
              trigger: ['blur', 'change'],
              
            },
            {
              // 自定义验证函数，见上说明
              validator: (rule, value, callback) => {
                console.log(value)
                if (value === this.formData.password) {
                  return true
                } else {
                  return false
                }
              },
              message: '两次输入的密码不一致！',
              // 触发器可以同时用blur和change
              trigger: ['change', 'blur'],
            }
          ]
        }
      }
    },
    methods: {
      async submit() {
        await this.$refs.form.validate()
        const { username, password, nickname } = this.formData
        const res = await this.$http.post('/register', {
          username,
          password,
          nickname
        })
        this.$store.dispatch('login', res.data)
        this.$nav.switchTab('/pages/mine/mine')
      }
    }
  }
</script>

<style>
</style>